﻿using System;
using System.Collections;
using System.Xml;
using System.Text;
using System.Threading;
using System.Globalization;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;
using InfoJetSoft.Service.EscapeRule;

namespace InfoJetSoft.Service.Worker
{
	
	class FormBuildHTMLScriptWorker
	{
		/*
		 * Script中类型: 
		 * 1. 只需要在页面打开时运行一次,如一些配置.
		 * 2. 在主页面或Iframe中运行都可以,如alert
		 * 3. 只在iframe中运行
		 * 4. 既在iframe中又在主页面中运行.
		 * 5. 如果正在使用AJAX,则总是在主页面中运行.
		 * 
		 * 在UpdateRefresh中,PreScript在OnLoad前调用,Script在OnLoad后调用.
		 * 在初始显示页面时,则PreScript和Script都在OnLoad前调用.
		 */
		

		/*
		 * 目前需要考虑的一个新情况,在使用CMD_BUILD_BY_PARAMETERS重新构造表单之后,又重新显示在页面上.
		 * 简单说既保存后打开(Philip),这时因为正个页面所有内容都刷新了,所以一些JavaScript定义要像打开表单时一样进行定义.
		 */

		public static void buildHTMLScript(Form form)
		{
			XmlDocument doc = form.HtmlDoc;
			XmlElement root = doc.DocumentElement;

			//定义parent前缀,如果form.Command则是直接输出到页面上,否则是输出到IFrame中,应该使用parent.访问父文档中的对象.
			//如果是正在响应AJAX,同样,也不需要使用parent.前缀,因为AJAX中的代码是在主页面中通过eval()调用的.
			//如果是保存后重新显示,和打开表单时是一样的.
			string parent = "";
			//CID 0291 //2009.06.01 //ConfigUtil.UseAJAX()
			if( ( ( form.Command.Equals( JetConstant.CMD_BUILD_BY_TEMPLATE ) || 
					form.Command.Equals( JetConstant.CMD_BUILD_BY_XML ) ||
					form.Command.Equals( JetConstant.CMD_BUILD_BY_PARAMETERS )
					) && ( !FormUtil.isRebuildCommand( form ) ) ) 
				|| ConfigUtil.UseAJAX() )
			{
				parent = "";
			}
			else
			{
				parent = "parent.";
			}

			//------------------------- ScriptFunction 输出用户自己编写的JavaScript函数，因为可能包含<>等字符，所以需要特殊处理。 -----

			//因为ValueChange和Refresh都需要PreScript和Script，而Function需要PostFormat处理，所以独立出来。
			StringBuilder functionBuffer = new StringBuilder();

			//这些代码只需要在打开表单时输出。
			if( form.Command.Equals( JetConstant.CMD_BUILD_BY_TEMPLATE ) || 
				form.Command.Equals( JetConstant.CMD_BUILD_BY_XML ) ||
				form.Command.Equals( JetConstant.CMD_BUILD_BY_PARAMETERS ))
			{
				//输出ClientScriptButton响应函数。
				if( form.Manifest.FormConfiguration.ClientScriptButtonList != null )
				{
					foreach( FormConfigClientScriptButton clientScriptButton in form.Manifest.FormConfiguration.ClientScriptButtonList )
					{
						functionBuffer.Append( clientScriptButton.getClientCode() );
					}
				}

                //CID 0619 //2010.06.24 //Begin
                if (form.Manifest.HtmlScriptList != null)
                {
                    foreach (string htmlScript in form.Manifest.HtmlScriptList)
                    {
                        functionBuffer.Append( htmlScript );
                    }
                }
                //CID 0619 //2010.06.24 //End

                //CID 0629 //2010.07.30 //Begin
                if (form.Manifest.HtmlOnChangeList != null)
                {
                    functionBuffer.Append( "InfoJet_OnChangeTable = new Object();\r\n" );
                    foreach (HtmlOnChange htmlOnChange in form.Manifest.HtmlOnChangeList)
                    {
                        functionBuffer.Append("InfoJet_OnChangeTable[ '" + htmlOnChange.NodeName + "' ] = " + htmlOnChange.OnChange + "\r\n");
                    }
                }
                //CID 0629 //2010.07.30 //End

                //CID 0735 //2010.12.19 //Begin
                if (form.Manifest.HtmlOnClickList != null)
                {
                    functionBuffer.Append("InfoJet_OnClickTable = new Object();\r\n");
                    foreach (HtmlOnClick htmlOnClick in form.Manifest.HtmlOnClickList)
                    {
                        functionBuffer.Append("InfoJet_OnClickTable[ '" + htmlOnClick.ViewId + "#" + htmlOnClick.Id + "' ] = " + htmlOnClick.OnClick + "\r\n");
                    }
                }
                //CID 0735 //2010.12.19 //End
			}

			//形成<!--###和###-->特征字串，在FormXhtmlPostFormatWorker中删除，解决“return statement outside of function”问题。
			functionBuffer.Insert( 0, "#Script#" );
			functionBuffer.Append( "#Script#" );

			XmlElement functionElement = doc.CreateElement( "script" );
			functionElement.SetAttribute( JetConstant.HTML_id, JetConstant.FucntionId );
			//将脚本放在comment里，解决>在InnerText中变成&gt;问题，但是却带来“return statement outside of function”问题。
			XmlComment functionComment = doc.CreateComment( functionBuffer.ToString() );
			functionElement.AppendChild( functionComment );
			root.AppendChild( functionElement );
			
			//------------------------- PreScript 主要是定义,只在打开表单时输出 ------------------------------------------------

			StringBuilder preScriptBuffer = new StringBuilder();
			
			//只需要在打开表单时输出代码。
			if( form.Command.Equals( JetConstant.CMD_BUILD_BY_TEMPLATE ) || 
				form.Command.Equals( JetConstant.CMD_BUILD_BY_XML ) || 
				form.Command.Equals( JetConstant.CMD_BUILD_BY_PARAMETERS ) ) //保存后重新显示.
			{
				//输出WebContext
				preScriptBuffer.Append( "InfoJet_WebContext = '" + form.Manifest.XSNConfig.WebContext + "';" );

				//CID 0471 //2009.11.30 //Begin
				NumberFormatInfo numberFormat = Thread.CurrentThread.CurrentCulture.NumberFormat;
				preScriptBuffer.Append( "InfoJet_NumberDecimalSeparator = '" + numberFormat.NumberDecimalSeparator + "';" );
				preScriptBuffer.Append( "InfoJet_NumberGroupSeparator = '" + numberFormat.NumberGroupSeparator + "';" );
				preScriptBuffer.Append( "InfoJet_CurrencyDecimalSeparator = '" + numberFormat.CurrencyDecimalSeparator + "';" );
				preScriptBuffer.Append( "InfoJet_CurrencyGroupSeparator = '" + numberFormat.CurrencyGroupSeparator + "';" );
				//CID 0471 //2009.11.30 //End

				if( !ConfigUtil.IsValidSubmit() )
				{
					preScriptBuffer.Append( "InfoJet_ValidSubmit = false;" );
				}

				//是否使用AJAX Postback.
				
				//CID 0134 //2008.10.05 //Begin
				//CID 0291 //2009.06.01 //Begin
				if( ConfigUtil.UseAJAX() )
				{
					preScriptBuffer.Append( "InfoJet_UseAjax = true;" );
				}
				else
				{
					preScriptBuffer.Append( "InfoJet_UseAjax = false;" );
				}
				//CID 0291 //2009.06.01 //End
				//CID 0134 //2008.10.05 //End

				//是否显示进度.
				//CID 0077 //2008.08.04 //Begin
				string showProgress = ConfigUtil.ShowProgress();
				if( showProgress != null )
				{
					if( showProgress.Equals( "true" ) || showProgress.Equals( "modaless" ) )
					{
						preScriptBuffer.Append( "InfoJet_ShowProgress = true;" );
					}
					else if( showProgress.Equals( "modal" ) )
					{
						preScriptBuffer.Append( "InfoJet_ShowProgress = true;" );
						preScriptBuffer.Append( "InfoJet_IsCanvasTranparent = false;" );
					}
				}
				//CID 0077 //2008.08.04 //End

				//CID 0400 //2009.12.09 //Begin
				bool scrollIntoView = ConfigUtil.ScrollFollowUpFormViewIntoView();
				if( scrollIntoView )
				{
					preScriptBuffer.Append( "InfoJet_ScrollFollowUpFormViewIntoView = true;" );
				}
				//CID 0400 //2009.12.09 //End

				if( form.Manifest.FormConfiguration.NoValidation || ConfigUtil.NoValidation( form ) )
				{
					preScriptBuffer.Append( "InfoJet_NoValidation = true;" );
				}

				if( form.Manifest.FormConfiguration.NoPostback || ConfigUtil.NoPostback() )
				{
					preScriptBuffer.Append( "InfoJet_NoPostback = true;" );
				}

                string correctFirstMessage = ConfigUtil.CorrectFirstMessage();
                if (correctFirstMessage != null)
                {
                    preScriptBuffer.Append("InfoJet_LocalResources['CorrectFirstMessage'] = '" + correctFirstMessage + "';");
                }

				if( ConfigUtil.EnableUnderline() )
				{
					preScriptBuffer.Append( "InfoJet_EnableUnderline = true;" );
				}

				string selectFileMessage = ConfigUtil.SelectFileMessage();
				preScriptBuffer.Append( "InfoJet_SelectFileMessage = '" + selectFileMessage + "';" );

				//输出ReplaceBrowserContextMenu和DisplayMenuArrow的定义.
                //CID 1554 //2012.12.24 //Begin
				if( form.JetContext.ReplaceBrowserContextMenu )
				{
					preScriptBuffer.Append( "InfoJet_ReplaceBrowserContextMenu = true;" );
				}
				else
				{
					string replaceContextMenu = (string)form.ParamTable[ JetConstant.XDOC_PARAM_REPLACE_CONTEXT_MENU ];
					if( replaceContextMenu != null && replaceContextMenu.Equals( JetConstant.HTML_true ) )
					{
						preScriptBuffer.Append( "InfoJet_ReplaceBrowserContextMenu = true;" );
					}
				}
                //CID 1554 //2012.12.24 //End
				if( !form.JetContext.DisplayMenuArrow )
				{
					preScriptBuffer.Append( "InfoJet_ShowMenuArrow = false;" );
				}
				else
				{
					string displayMenuArrow = (string)form.ParamTable[ JetConstant.XDOC_PARAM_DISPLAY_MENU_ARROW ];
					if( displayMenuArrow != null && displayMenuArrow.Equals( JetConstant.HTML_false ) )
					{
						preScriptBuffer.Append( "InfoJet_ShowMenuArrow = false;" );
					}
				}

				if( ConfigUtil.IsBrowserQuick() )
				{
					preScriptBuffer.Append( "InfoJet_BrowserQuick = true;" );
				}

				//输出ValidFormButton响应函数。
				if( form.Manifest.FormConfiguration.ValidFormButtonList != null )
				{
					foreach( FormConfigValidFormButton validFormButton in form.Manifest.FormConfiguration.ValidFormButtonList )
					{
						validFormButton.run( form.Manifest );
						preScriptBuffer.Append( validFormButton.getClientCode() );
					}
				}

				//CID 0023 //2008.06.19 //Begin
				string saveAsPage = ConfigUtil.SaveAsPage();
				if( saveAsPage != null )
				{
					//CID 0147 //2008.11.03 //Begin
					if( saveAsPage.StartsWith( "~" ) )
					{
						saveAsPage = saveAsPage.Replace( "~", PathUtil.getAppPath(form.HttpContext) );
					}
					//CID 0147 //2008.11.03 //End
					preScriptBuffer.Append( "InfoJet_SaveAsPage = '" + saveAsPage + "';" );
				}
				//CID 0023 //2008.06.19 //Begin

				//CID 0048 //2008.07.15 //Begin
				bool enableReplaceGroupingSymbol = ConfigUtil.EnableReplaceGroupingSymbol();
				if( enableReplaceGroupingSymbol )
				{
					preScriptBuffer.Append( "InfoJet_EnableReplaceGroupingSymbol = true;" );
				}
				//CID 0048 //2008.07.15 //End

				//CID 0262 //2009.03.26 //Begin
				if( form.Manifest.FormConfiguration.ViewSwitchValiation )
				{
					preScriptBuffer.Append( "InfoJet_ViewSwitchValidation = true;" );
				}
				//CID 0262 //2009.03.26 //End

				//CID 0526 //2010.03.30 //Begin
				if( form.Manifest.NonProofingNodeNameArrays != null )
				{
					preScriptBuffer.Append( form.Manifest.NonProofingNodeNameArrays );
				}
				//CID 0526 //2010.03.30 //End

				//CID 0544 //2010.05.12 //Begin
				bool hideTryAgainNotification = ConfigUtil.HideTryAgainNotification();
				if( hideTryAgainNotification )
				{
					preScriptBuffer.Append( "InfoJet_HideTryAgainNotification = true;" );
				}
				//CID 0544 //2010.05.12 //End

                //CID 0670 //2010.10.04 //Begin
                bool formatReadonlyView = ConfigUtil.FormatReadonlyView();
                if (formatReadonlyView)
                {
                    preScriptBuffer.Append("InfoJet_FormatReadonlyView = true;");
                }
                //CID 0785 //2011.02.22 //End

                //CID 0664 //2010.10.07 //Begin
                bool enableFormFieldsCache = form.Manifest.FormFieldsCacheEnabled;
                if(enableFormFieldsCache)
                {
                    preScriptBuffer.Append("InfoJet_EnableFormFieldsCache = true;");
                }
                //CID 0664 //2010.10.07 //End

                //CID 0880 //2011.04.30 //Begin
                string pingParameter = ConfigUtil.PingParameter();
                if (pingParameter != null)
                {
                    preScriptBuffer.Append("InfoJet_PingParameter = \"" + pingParameter + "\";");
                }
                string pingInterval = ConfigUtil.PingInterval();
                if (pingInterval != null)
                {
                    preScriptBuffer.Append("InfoJet_PingInterval = " + pingInterval + ";");
                }
                //CID 0880 //2011.04.30 //End

                //CID 1147 //2012.03.28 //Begin
                if (ConfigUtil.RedAsteriskOTA())
                {
                    preScriptBuffer.Append("InfoJet_RedAsteriskOTA = true;");
                }
                //CID 1147 //2012.03.28 //End

                //CID 1366 //2012.10.04 //Begin
                if (ConfigUtil.EnableRichText())
                {
                    if (ConfigUtil.EditRichTextOnFocus)
                    {
                        preScriptBuffer.Append("InfoJet_EditRichTextOnFocus = true;");
                    }
                }
                //CID 1366 //2012.10.04 //End

                //CID 1422 //2012.10.31 //Begin
                if (ConfigUtil.EnablePlaceholderUI())
                {
                    preScriptBuffer.Append("InfoJet_EnablePlaceholderUI = true;");
                }
                //CID 1422 //2012.10.31 //End
			}

			XmlElement preScriptElement = doc.CreateElement( "script" );
			preScriptElement.SetAttribute( JetConstant.HTML_id, JetConstant.PreScriptId );
			preScriptElement.InnerText = preScriptBuffer.ToString();
			root.AppendChild( preScriptElement );

			//------------------------- Script 主要是操作 ------------------------------------------------

			StringBuilder scriptBuffer = new StringBuilder();

            //CID 0500 //2010.07.29 //Begin
            if (ConfigUtil.EnableControlPSVI())
            {
                scriptBuffer.Append("InfoJet_PSVITable = new Object();\r\n");
                foreach (ParsedPSVI psvi in form.PSVITable.Values)
                {
                    if (psvi.Type != null)
                    {
                        scriptBuffer.Append("InfoJet_PSVITable[ '");
                        scriptBuffer.Append(psvi.ID);
                        scriptBuffer.Append("' ] = { type:'");
                        scriptBuffer.Append(psvi.Type);
                        scriptBuffer.Append("', nillable: '");
                        scriptBuffer.Append(psvi.Nillabe);
                        if (psvi.Pattern != null)
                        {
                            scriptBuffer.Append("', pattern: '");
                            scriptBuffer.Append(psvi.Pattern);
                        }
                        if (psvi.Enumeration != null)
                        {
                            scriptBuffer.Append("', enumeration: '");
                            scriptBuffer.Append(psvi.Enumeration);
                        }
                        if (psvi.Length != null)
                        {
                            scriptBuffer.Append("', length: '");
                            scriptBuffer.Append(psvi.Length);
                        }
                        if (psvi.MaxLength != null)
                        {
                            scriptBuffer.Append("', maxLength: '");
                            scriptBuffer.Append(psvi.MaxLength);
                        }
                        if (psvi.MinLength != null)
                        {
                            scriptBuffer.Append("', minLength: '");
                            scriptBuffer.Append(psvi.MinLength);
                        }
                        if (psvi.MinInclusive != null)
                        {
                            scriptBuffer.Append("', minInclusive: '");
                            scriptBuffer.Append(psvi.MinInclusive);
                        }
                        if (psvi.MaxInclusive != null)
                        {
                            scriptBuffer.Append("', maxInclusive: '");
                            scriptBuffer.Append(psvi.MaxInclusive);
                        }
                        if (psvi.MinExclusive != null)
                        {
                            scriptBuffer.Append("', minExclusive: '");
                            scriptBuffer.Append(psvi.MinExclusive);
                        }
                        if (psvi.MaxExclusive != null)
                        {
                            scriptBuffer.Append("', maxExclusive: '");
                            scriptBuffer.Append(psvi.MaxExclusive);
                        }
                        if (psvi.MaxExclusive != null)
                        {
                            scriptBuffer.Append("', maxExclusive: '");
                            scriptBuffer.Append(psvi.MaxExclusive);
                        }
                        if (psvi.FractionDigits != null)
                        {
                            scriptBuffer.Append("', fractionDigits: '");
                            scriptBuffer.Append(psvi.FractionDigits);
                        }
                        if (psvi.TotalDigits != null)
                        {
                            scriptBuffer.Append("', totalDigits: '");
                            scriptBuffer.Append(psvi.TotalDigits);
                        }
                        if (psvi.WhiteSpace != null)
                        {
                            scriptBuffer.Append("', whiteSpace: '");
                            scriptBuffer.Append(psvi.WhiteSpace);
                        }
                        scriptBuffer.Append("' };\r\n");
                    }
                }
            }
            //CID 0500 //2010.07.29 //End

            //CID 0749 //2011.09.04 //Begin
            if (form.SignedDataInfoList != null)
            {
                //CID 1038 //2012.01.06 //Begin
                bool hasError = false;
                //CID 1038 //2012.01.06 //End
                foreach (SignedDataInfo signedDataInfo in form.SignedDataInfoList)
                {
                    foreach (SignedElementInfo signedElementInfo in signedDataInfo.SignatureElementList)
                    {
                        //CID 1021 //2011.09.29 //Begin
                        if (signedElementInfo.Status != SignedStatus.Valid)
                        {
                            //CID 1552 //2013.01.11 //CMD_UPDATE_AddSignature Removed.
                            if (form.Command.Equals(JetConstant.CMD_BUILD_BY_XML))
                            {
                                //CID 1038 //2012.01.06 //Begin
                                hasError = true;
                                break;
                                //CID 1038 //2012.01.06 //End
                            }
                        }
                        //CID 1021 //2011.09.29 //End
                    }
                }
                //CID 1038 //2012.01.06 //Begin
                if (hasError)
                {
                    scriptBuffer.Append("alert( 'There is one or more problems about the digital signature in this form.' );");
                }
                //CID 1038 //2012.01.06 //End
            }
            //CID 0749 //2011.09.04 //End

			foreach( string modalMessage in form.ModalMessageList )
			{
                scriptBuffer.Append( "alert( '" + ScriptHtmlUtil.formatMessage( modalMessage ) + "' );" );
			}

			if( form.ErrCondValiModalMessage != null && form.ErrCondValiModalMessage.Length > 0 )
			{
                scriptBuffer.Append("alert( '" + ScriptHtmlUtil.formatMessage(form.ErrCondValiModalMessage) + "' );");
			}

			//CID 0400 //2009.12.01 //Begin
			//根据视图输出,可能每个视图都不一样.
			View currentView = form.Manifest.getView(form.ViewId);
            //2012.12.13 Sunny Begin
            scriptBuffer.Append(parent + "InfoBus_CurrentViewName = '" + currentView.Name + "';");
            //2012.12.13 Sunny End
            //scriptBuffer.Append(parent + "InfoJet_CurrentViewName = '" + form.View.Name + "';");
			if( FormUtil.isReadonly( form ) )
			{
				//如果表单是只读的,所有视图都将是只读的. 
				//先设置InfoJet_IsReadonly为true,InfoJet_IsReadonly为true时,InfoJet_Init将不构造xdoc_menu.
				//InfoJet_IsReadonly只用于表单只读,不用于视图只读.
				scriptBuffer.Append( parent + "InfoJet_SetViewReadonly();" );
			}
			else
			{
				//如果当前view是readonly,则调用InfoJet_SetViewReadonly().
				//同时XSNManifestMenuParseWorker中Readonly的View不输出View中定义的菜单(主要是XmlToEdit菜单).
				//InfoJet_SetViewReadonly主要是禁用控件.
				if( currentView.IsReadonly )
				{
					scriptBuffer.Append( parent + "InfoJet_SetViewReadonly();" );
				}
			}
			//CID 0400 //2009.12.01 //End

			//CID 0450 //2009.11.04 //Begin
			//在InfoJet_SelectText()和InfoJet_SetViewReadonly()之前.
			if( form.Command.Equals( JetConstant.CMD_BUILD_BY_TEMPLATE ) || 
				form.Command.Equals( JetConstant.CMD_BUILD_BY_XML ) ||
				//CID 0400 //2009.12.02 //保存后重新显示也需要自动设置焦点.
				form.Command.Equals( JetConstant.CMD_BUILD_BY_PARAMETERS) )
			{
				//CID 0400 //2009.12.02 //Begin
				form.IsOnOpenView = true;
				//CID 0400 //2009.12.02 //End
				//打开表单时,InfoJet_OnOpenView中自动设置光标到第一个控件.
				scriptBuffer.Append( parent + "InfoJet_OnOpenView(true);" );
				//CID 0526 //2010.03.31 //Begin
				if( form.Manifest.NonProofingNodeNameArrays != null )
				{
					scriptBuffer.Append( parent + "InfoJet_CurrentViewName = '" + form.View.Name + "';" );
				}
				//CID 0526 //2010.03.31 //End
			}
			else
			{
				//在切换视图之后将视图滚动到顶部.
				//这个操作不在打开表单时执行,因为这会影响宿主页面的行为.
				if( form.Command.Equals(JetConstant.CMD_UPDATE_View) || form.IsViewSwitched )
				{
					//CID 0400 //2009.12.02 //Begin
					form.IsOnOpenView = true;
					//CID 0400 //2009.12.02 //End
					//打开表单时,InfoJet_OnOpenView中自动设置光标到第一个控件.
					scriptBuffer.Append( parent + "InfoJet_OnOpenView(false);" );
					//CID 0526 //2010.03.31 //Begin
					if( form.Manifest.NonProofingNodeNameArrays != null )
					{
						scriptBuffer.Append( parent + "InfoJet_CurrentViewName = '" + form.View.Name + "';" );
					}
					//CID 0526 //2010.03.31 //End
				}
			}
			//CID 0450 //2009.11.04 //End

			//执行由表单代码View.SelectText()转换成的JavaScript代码.
			if( form.SelectTextNode != null )
			{
				string jetId = null;
				if( form.SelectTextNode.XmlNode == null )
				{
					jetId = form.SelectTextNode.JetId;
				}
				else
				{
					jetId = DOMUtil.getNodeJetId( form.SelectTextNode.XmlNode );
				}
				scriptBuffer.Append( parent + "InfoJet_SelectText('" + jetId + "', '" + form.SelectTextNode.ControlId + "');" );
			}

			//CID 0474 //2009.12.23 //Begin
			if( form.Command.Equals( JetConstant.CMD_UPDATE_Refresh ) && form.ValueChangeNode != null )
			{
				string isUpdated = "false";
				if( form.Logger.IsUpdatedOnChange )
				{
					isUpdated = "true";
				}
				scriptBuffer.Append( parent + "InfoJet_CheckCachedPostback(" + isUpdated + ");" );
			}
			//CID 0474 //2009.12.23 //End

			//当打开表单,切换视图时焦点显示任务窗格.
			if( form.Command.Equals( JetConstant.CMD_BUILD_BY_TEMPLATE ) || 
				form.Command.Equals( JetConstant.CMD_BUILD_BY_XML ) ||
				form.Command.Equals( JetConstant.CMD_UPDATE_View ) || 
				form.Command.Equals( JetConstant.CMD_UPDATE_Button ) )
			{
				//如果ShowTaskPaneOnlyWhileButtonClicked为true,除了CMD_UPDATE_Button其它命令不打开TaskPane.
				if( form.Command.Equals( JetConstant.CMD_UPDATE_Button ) )
				{
					//只有代码调用了TaskPaneObject.Navigate, form.TaskPane才会存在.
					if( form.TaskPane != null )
					{
                        //CID 0618 //2010.07.05 //isResourceFileEnabled
                        if (PathUtil.isResourceFileEnabled(form.Manifest))
						{
                            //CID 0618 //2010.07.05 //Begin
                            scriptBuffer.Append("var taskPaneWindow = " + parent + "window.open( '" + ResourceFileUtil.getResourceFileUrl(form.Manifest, form.TaskPane.Href) + "', null, " + ConfigUtil.TaskPaneFeatures() + " );");
                            //CID 0618 //2010.07.05 //End
                            scriptBuffer.Append("taskPaneWindow.focus();");
						}
					}
				}
				//如果是其它情况
				else
				{
					//自动显示定义的第一个TaskPane.
					if( form.Manifest.TaskPaneList != null )
					{
						//同时ShowTaskPaneOnlyWhileButtonClicked未启用.
						if( !ConfigUtil.ShowTaskPaneOnlyWhileButtonClicked() )
						{
                            //CID 0618 //2010.07.05 //isResourceFileEnabled
                            if (PathUtil.isResourceFileEnabled(form.Manifest))
                            {
								TaskPane taskPane = (TaskPane)form.Manifest.TaskPaneList[0];
                                //CID 0618 //2010.07.05 //Begin
                                scriptBuffer.Append("var taskPaneWindow = " + parent + "window.open( '" + ResourceFileUtil.getResourceFileUrl(form.Manifest, taskPane.Href) + "', null, " + ConfigUtil.TaskPaneFeatures() + " );");
                                //CID 0618 //2010.07.05 //End
                                scriptBuffer.Append( "taskPaneWindow.focus();" );
							}
						}
					}
				}
			}

			//如果MailEnvelope可见
			if( form.MailEnvelope != null && form.MailEnvelope.Visible )
			{
				//调用MailEnvelope.click(),显示邮件软件.
				scriptBuffer.Append( parent + "document.getElementById('" + JetConstant.XDOC_MailEnvelope + "').click();" );
			}

			if( form.Manifest.FormConfiguration.EnableScriptX || ConfigUtil.EnableScriptX()  )
			{
				if( currentView.PrintHeader != null )
				{
					scriptBuffer.Append( parent + "factory.printing.header = " + parent  + "document.getElementById('" + JetConstant.XDOC_PrintSetting + "').getAttribute('header');");
				}
				if( currentView.PrintFooter != null )
				{
					scriptBuffer.Append( parent + "factory.printing.footer = " + parent  + "document.getElementById('" + JetConstant.XDOC_PrintSetting + "').getAttribute('footer');");
				}
				if( !currentView.Portrait )
				{
					scriptBuffer.Append( parent + "factory.printing.portrait = false;");
				}
				if( currentView.TopMargin >= 0 )
				{
					scriptBuffer.Append( parent + "factory.printing.topMargin = " + parent  + "document.getElementById('" + JetConstant.XDOC_PrintSetting + "').getAttribute('topMargin');");
				}
				if( currentView.LeftMargin >= 0 )
				{
					scriptBuffer.Append( parent + "factory.printing.leftMargin = " + parent  + "document.getElementById('" + JetConstant.XDOC_PrintSetting + "').getAttribute('leftMargin');");
				}
				if( currentView.BottomMargin >= 0 )
				{
					scriptBuffer.Append( parent + "factory.printing.bottomMargin = " + parent  + "document.getElementById('" + JetConstant.XDOC_PrintSetting + "').getAttribute('bottomMargin');");
				}
				if( currentView.RightMargin >= 0 )
				{
					scriptBuffer.Append( parent + "factory.printing.rightMargin = " + parent  + "document.getElementById('" + JetConstant.XDOC_PrintSetting + "').getAttribute('rightMargin');");
				}
			}

			//只是在CMD_BUILD_BY_TEMPLATE,CMD_BUILD_BY_XML,CMD_UPDATE_Submit,CMD_UPDATE_Query,CMD_UPDATE_Button时显示登录对话框.
			//但是实际上可能还有其它情况,尤其是CMD_UPDATE_Refresh,但是这时很难在显示对话框后重新提交上一请求.
			//所以目前只支持这几种情况.
			//似乎应该找到另外一种更合适的登录方式.
			if( form.Command.Equals( JetConstant.CMD_BUILD_BY_TEMPLATE ) || 
				form.Command.Equals( JetConstant.CMD_BUILD_BY_XML ) || 
				form.Command.Equals( JetConstant.CMD_UPDATE_Submit ) || 
				form.Command.Equals( JetConstant.CMD_UPDATE_Query ) || 
				form.Command.Equals( JetConstant.CMD_UPDATE_Button ) )
			{
				if(  form.UnauthorizedConnectionList.Count > 0 )
				{
					scriptBuffer.Append( "InfoJet_Unauthorized = true;" );
					scriptBuffer.Append( "var unauthArray = new Array();" );
					foreach( UnauthorizedConnection unauthDataObject in form.UnauthorizedConnectionList )
					{
                        scriptBuffer.Append("var unauth = {name:'' , auth:'', realm:'', hidden:false};");
						scriptBuffer.Append( "unauth.name = '" +  ScriptHtmlUtil.formatMessage( unauthDataObject.ConnectionName ) + "';" );
						scriptBuffer.Append( "unauth.auth = '" +  ScriptHtmlUtil.formatMessage(unauthDataObject.AuthenticateType ) + "';" );
						scriptBuffer.Append( "unauth.realm = '" +  unauthDataObject.Realm + "';" );
						scriptBuffer.Append( "unauthArray[ unauthArray.length ] = unauth;" );
					}
					
					scriptBuffer.Append( "if( window.showModalDialog( '" + form.Manifest.XSNConfig.WebContext + "js/unauthorized_dialog.htm', new Array( parent, unauthArray ), 'dialogWidth:470px;dialogHeight:165px;help:no;') == 1){ " );
					if( form.Command.Equals( JetConstant.CMD_BUILD_BY_TEMPLATE ) )
					{
						scriptBuffer.Append( parent + "InfoJet_RebuildByCommand( 'Build_Template');" );
					}
					if( form.Command.Equals( JetConstant.CMD_BUILD_BY_XML ) )
					{
						scriptBuffer.Append( parent + "InfoJet_RebuildByCommand( 'Build_XML');" );
					}
					if( form.Command.Equals(  JetConstant.CMD_UPDATE_Submit ) )
					{
						scriptBuffer.Append( parent + "InfoJet_DoSubmitDirect();" );
					}
					if( form.Command.Equals(  JetConstant.CMD_UPDATE_Query ) )
					{
						scriptBuffer.Append( parent + "InfoJet_DoQueryDirect();" );
					}
					if( form.Command.Equals(  JetConstant.CMD_UPDATE_Button ) )
					{
						string ctrlId = (string)form.ParamTable[ JetConstant.XDOC_PARAM_BUTTON ];
						string buttonSource = (string)form.ParamTable[ JetConstant.XDOC_PARAM_BUTTON_SOURCE ];
						scriptBuffer.Append( parent + "InfoJet_DoButtonDirect( '" + ctrlId + "', '" + buttonSource + "' );" );
					}
					scriptBuffer.Append( "}" );
				}
			}

			//打印文档.
			if( form.IsPrintOut )
			{
				scriptBuffer.Append( parent + "print();" );
			}

			//如果有ClientCode,输出.
			//这里的ClientCode还是放在focus之后比较好,目前不调用RunClientCodeOnly而只调用ClientCode的地方是用Word打开MHT(Build 2007.07.09).
			if( form.ClientCodeList != null )
			{
				foreach( string clientCode in form.ClientCodeList )
				{
					scriptBuffer.Append( clientCode );
				}
			}

			//CID 0400 //2009.12.01 //Begin
			//CID 0369 //2009.07.18 //Begin
			if( form.NewFormPublishUrl != null )
			{
				if( form.NewFormPublishUrl.Equals( form.HttpContext.Server.UrlEncode( form.Manifest.PublishUrl ) ) )
				{
					scriptBuffer.Append( parent + "InfoJet_OpenNewForm('" + form.NewFormPublishUrl  + "', true);" );
				}
				else
				{
					scriptBuffer.Append( parent + "InfoJet_OpenNewForm('" + form.NewFormPublishUrl  + "', false);" );
				}
			}
			//CID 0369 //2009.07.18 //End
			//CID 0400 //2009.12.01 //End
			
			//输出关闭文档的脚本
			if( form.IsCloseDoc && ( form.Command.Equals( JetConstant.CMD_UPDATE_Button ) || form.Command.Equals( JetConstant.CMD_UPDATE_Submit ) ) )
			{
				if( form.IsPromptToSaveChanges )
				{
					scriptBuffer.Append( parent + "InfoJet_Try2CloseWindow(true);" );
				}
				else
				{
					scriptBuffer.Append( parent + "InfoJet_Try2CloseWindow(false);" );
				}
			}

			XmlElement scriptElement = doc.CreateElement( "script" );
			scriptElement.SetAttribute( JetConstant.HTML_id, JetConstant.ScriptId );
			scriptElement.InnerText = scriptBuffer.ToString();
			root.AppendChild( scriptElement );
		}
	}

}